package itheima04;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/*
    写一个"框架"，不能改变该类的任何代码的前提下，可以帮我们创建任意类的对象，并且执行其中任意方法
    步骤:
        1.创建一个配置文件(config.properties),存储键值对  ClassName=domain.Animal MethodName=eat
        2.读取(IO+Properties)配置文件,获取String类型的类名称和方法名称
        3.获取Class类型的对象(三种方式,建议使用第三种forName)
        4.获取方法对象
        5.执行方法对象
 */
/*public class Demo06Reflect {
    public static void main(String[] args) throws Exception {
        //2.读取(IO+Properties)配置文件,获取String类型的类名称和方法名称
        Properties props = new Properties();
        props.load(new FileInputStream("day15\\config.properties"));
        //类名称
        String className = props.getProperty("ClassName");
        String methodName = props.getProperty("MethodName");
        //domain.Dog
        System.out.println(className);
        //sleep
        System.out.println(methodName);

        //3.获取Class类型的对象(三种方式,建议使用第三种forName)
        Class<?> c = Class.forName(className);

        //4.获取方法
        Method method = c.getMethod(methodName);

        //方法的执行,需要对象的支持
        Object obj = c.newInstance();
        //domain.Dog@19dfb72a,调用Dog的无参构造
        System.out.println(obj);
        //5.执行方法对象
        //狗打瞌睡......
        method.invoke(obj);

    }
}*/

public class Demo06Reflect {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Properties properties=new Properties();
        FileInputStream fileInputStream=new FileInputStream("day15\\config.properties");

        properties.load(fileInputStream);

        //根据键获取值
        String property = properties.getProperty("ClassName");
        String property1 = properties.getProperty("MethodName");

        //domain.Dog
        System.out.println(property);
        //sleep
        System.out.println(property1);

        /* int read =0;
         //35个字节
        byte[] bytes=new byte[1024];
        while (( read=fileInputStream.read(bytes))!=-1){
            //#ClassName=domain.Animal
            //ClassName=domain.Dog
            //#MethodName=eat
            //MethodName=sleep
            System.out.println(new String(bytes,0,read));
        }*/

        Class<?>c=Class.forName(property);

        Method method = c.getMethod(property1);

        //public void domain.Dog.sleep()
        System.out.println(method);
        //方法的执行,
        Object o = c.newInstance();
        //domain.Dog@17c68925
        System.out.println(o);
        //狗打瞌睡......
        method.invoke(o);

    }
}